package com.example.rjb_shoping.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class JsonUtil {
    private static int status; // 状态码
    private static String error; // 错误信息
    private static Object data; // 返回数据

    public JsonUtil(int status, String error, Object data) {
        this.status = status;
        this.error = error;
        this.data = data;
    }

    public JsonUtil(int status, Object data) {
        this.status = status;
        this.data = data;
    }

    public JsonUtil(int status, String error) {
        this.status = status;
        this.error = error;
    }

    public JsonUtil(Object data) {
        this.status = 200;
        this.data = data;
    }

    /**
     * 格式化返回值
     *
     * @return json字符串
     */
    public String getJson() {
        ObjectMapper om = new ObjectMapper();
        String str = "";
        Map<String, Object> list = new HashMap<>();
        list.put("status", status);
        list.put("error", error);
        list.put("data", data);
        try {
            str = om.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return str;
    }
}
